package com.google.project.client.HumanResources;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.project.client.Service.SpecializeService;
import com.google.project.client.Service.SpecializeServiceAsync;
import com.google.project.client.Service.UsersService;
import com.google.project.client.Service.UsersServiceAsync;
import com.google.project.shared.SpecializeDTO;
import com.google.project.shared.UsersDTO;

public class HMCreateEmployee extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	
	@UiField Button btnSave;
	@UiField TextBox txtUserCode;
	@UiField TextBox txtFullName;
	@UiField DateBox dbBirthday;
	@UiField TextBox txtHomeTown;
	@UiField RadioButton radMale;
	@UiField RadioButton radFemale;
	@UiField TextBox txtAddress;
	@UiField TextBox txtPhone;
	@UiField TextBox txtEmail;
	@UiField TextBox txtCMT;
	@UiField Button btnCancel;
	@UiField TextArea txtAreaDescription;
	@UiField ListBox cbExperience;
	@UiField ListBox cbSpecialize;
	@UiField Button btnReinit;
	
	private UsersDTO currentUser = new UsersDTO();
	
	private final UsersServiceAsync userService = GWT.create(UsersService.class);
	private final SpecializeServiceAsync specService = GWT.create(SpecializeService.class);
	private final List<SpecializeDTO> specializeDTOList = new ArrayList<SpecializeDTO>();
	private final List<UsersDTO> userList = new ArrayList<UsersDTO>();
	interface Binder extends UiBinder<Widget, HMCreateEmployee> {
	}

	public HMCreateEmployee() {
		initWidget(binder.createAndBindUi(this));
		dbBirthday.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		initCbSpecialize();
		initCbExperient();
	}

	public HMCreateEmployee(String userId) {
		initWidget(binder.createAndBindUi(this));
		dbBirthday.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		initCbExperient();
		getUserInfo(userId);
	}
	public void initCbExperient() {
		cbExperience.addItem("---Chọn---", "0");
		cbExperience.addItem("< 1 năm", "1");
		cbExperience.addItem("1-3 năm", "2");
		cbExperience.addItem("3-5 năm", "3");
		cbExperience.addItem("5-10 năm", "4");
		cbExperience.addItem("> 10 năm", "5");
		cbExperience.setSelectedIndex(0);
	}

	public void initCbSpecialize() {
		specService.getSpecList(new AsyncCallback<List<SpecializeDTO>>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(List<SpecializeDTO> result) {
				cbSpecialize.addItem("---Chọn---", "0");
				for (SpecializeDTO specializeDTO : result) {
					specializeDTOList.add(specializeDTO);
					cbSpecialize.addItem(specializeDTO.getSpecializeName(), specializeDTO.getId());
				}
				if(currentUser.getUserId() != null) {
					displayUserInfo();
				} else {
					userService.getUserList(new AsyncCallback<List<UsersDTO>>() {

						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
							
						}

						@Override
						public void onSuccess(List<UsersDTO> result) {
							// TODO Auto-generated method stub
							for(UsersDTO user : result) {
								userList.add(user);
							}
						}
					});
				}
			}
		});
		cbSpecialize.setSelectedIndex(0);
	}
	private void getUserInfo(String userId) {
		// TODO Auto-generated method stub
		userService.getUserById(userId, new AsyncCallback<UsersDTO>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Có lỗi trong quá trình Cập nhật!");
			}

			@Override
			public void onSuccess(UsersDTO result) {
				currentUser = result;
				initCbSpecialize();
			}

		});
	}

	private void displayUserInfo() {
		txtUserCode.setText(currentUser.getUserCode());
		txtUserCode.setEnabled(false);
		txtFullName.setText(currentUser.getFullName());
		dbBirthday.setValue(new Date(currentUser.getBirthday()));
		txtHomeTown.setText(currentUser.getHometown());
		if(currentUser.getSex() == 0){
			radMale.setValue(true);
			radFemale.setValue(false);
		} else if(currentUser.getSex() == 1) {
			radMale.setValue(false);
			radFemale.setValue(true);
		}
		txtCMT.setValue(currentUser.getIdCard());
		txtAddress.setValue(currentUser.getAddress());
		txtPhone.setValue(currentUser.getPhoneNumber());
		int index = 0;
		for(int i = 0; i <  specializeDTOList.size(); i++) {
			if(currentUser.getSpecializeID().equalsIgnoreCase(specializeDTOList.get(i).getId())) {
				index = i;
			}
		}
		cbSpecialize.setSelectedIndex(index + 1);
		txtEmail.setValue(currentUser.getEmail());
		int experientI = currentUser.getExperient();
		cbExperience.setSelectedIndex(experientI);
		txtAreaDescription.setValue(currentUser.getDescription());
	}

	@UiHandler("btnSave")
	void onBtnSaveClick(ClickEvent event) {
		if(validateData()) {
			getFormValues();
			if (currentUser.getUserId() == null) {
				userService.addUser(currentUser,
						new AsyncCallback<UsersDTO>() {
							@Override
							public void onSuccess(UsersDTO result) {
								clearForm();
								Window.alert("Thêm mới thành công!");
								
							}
							@Override
							public void onFailure(Throwable caught) {
								Window.alert("Có lỗi trong quá trình thêm mới!");
							}
						});
			} else {
				userService.updateUser(currentUser, new AsyncCallback<Void>() {
					
					@Override
					public void onSuccess(Void result) {
						// TODO Auto-generated method stub
						Window.alert("Cập nhật thành công!");
						HMEntrypoint.get().HMStaffList();
					}
					
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						Window.alert("Có lỗi trong quá trình cập nhật!");
					}
				});
			}
		}
	}

	private void getFormValues() {
		currentUser.setStatus("1");	//Mac dinh khi duoc tao la status = 1: chua co tai khoan
		currentUser.setUserCode(txtUserCode.getText().trim());
		currentUser.setFullName(txtFullName.getText().trim());
		if(dbBirthday.getValue() != null) {
			currentUser.setBirthday(dbBirthday.getValue().getTime());
		}
		currentUser.setHometown(txtHomeTown.getText().trim());
		if(radMale.getValue()) {
			currentUser.setSex(0);	//0 for Male
		} else {
			currentUser.setSex(1);	//1 for Female
		}
		currentUser.setAddress(txtAddress.getText().trim());
		currentUser.setPhoneNumber(txtPhone.getText().trim());
		currentUser.setEmail(txtEmail.getText().trim());
		int indexExp=cbExperience.getSelectedIndex();
		currentUser.setExperient(Integer.parseInt(cbExperience.getValue(indexExp)));
		currentUser.setIdCard(txtCMT.getText().trim());
		int indexSpec=cbSpecialize.getSelectedIndex();
		currentUser.setSpecializeID(cbSpecialize.getValue(indexSpec));
		String specName=cbSpecialize.getItemText(cbSpecialize.getSelectedIndex());
		currentUser.setSpecializeName(specName);
		currentUser.setJoinDate(new Date().getTime());
		currentUser.setDescription(txtAreaDescription.getText().trim());
	}
	
	private boolean validateData() {
		String userCode = txtUserCode.getText().trim();
		String fullName = txtFullName.getText().trim();
		String spec = cbSpecialize.getValue(cbSpecialize.getSelectedIndex());
		String exp = cbExperience.getValue(cbExperience.getSelectedIndex());
		
		//Validate Project Code
		if(userCode == null || userCode.equals("")) {
			Window.alert("Bạn phải nhập Mã nhân viên!");
			Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
		        public void execute () {
		        	txtUserCode.setFocus(true);
		        }
		    });
			return false;
		} else {
			if(currentUser.getUserId() == null) {
				for(UsersDTO userDTO : userList) {
					if(userDTO.getUserCode().equals(userCode)) {
						Window.alert("Mã nhân viên này đã tồn tại! Hãy nhập Mã khác!");
						Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
					        public void execute () {
					        	txtUserCode.setFocus(true);
					        }
					    });
						return false;
					}
				} 
			}
		}
		
		//Validate Full name
		if(fullName == null || fullName.equals("")) {
			Window.alert("Bạn phải nhập Họ tên nhân viên!");
			Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
		        public void execute () {
		        	txtFullName.setFocus(true);
		        }
		    });
			return false;
		}
		
		//Validate chuyen mon
		if(spec.equals("0")) {
			Window.alert("Bạn phải chọn chuyên môn!");
			Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
		        public void execute () {
		        	cbSpecialize.setFocus(true);
		        }
		    });
			return false;
		}
		//Validate kinh nghiem
		if(exp.equals("0")) {
			Window.alert("Bạn phải chọn kinh nghiệm!");
			Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
		        public void execute () {
		        	cbExperience.setFocus(true);
		        }
		    });
			return false;
		}
		
		return true;
	}
	
	private void clearForm(){
		txtUserCode.setText("");
		txtFullName.setText("");
		dbBirthday.setValue(null);
		txtHomeTown.setText("");
		radMale.setValue(true);
		radFemale.setValue(false);
		txtCMT.setValue("");
		txtAddress.setValue("");
		txtPhone.setValue("");
		cbSpecialize.setSelectedIndex(0);
		txtEmail.setValue("");
		cbExperience.setSelectedIndex(0);
		txtAreaDescription.setValue("");
	}
	@UiHandler("btnCancel")
	void onBtnCancelClick(ClickEvent event) {
		HMEntrypoint.get().HMStaffList();
	}
	
	@UiHandler("btnReinit")
	void onBtnReinitClick(ClickEvent event) {
		txtUserCode.setEnabled(true);
		clearForm();
	}
}
